<template>
	<el-scrollbar class="w-full h-full px-6">
		<div class="grid grid-cols-1 gap-3 xl:grid-cols-4">
			<div class="col-span-3 space-y-3">
				<datePicker @change="changeDate" />

				<div class="grid grid-flow-row grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5">
					<el-card v-for="(item, index) in statisticCard.kpi" :key="index" body-style="padding: 16px 0 10px;">
						<div class="flex justify-around divide-x divide-dashed">
							<el-statistic :title="item.title" :formatter="item.formatter" :value="item.value"
								class="flex-1 px-6" :value-style="item.getStyle ? item.getStyle(item.value) : ''">
								<template #title>
									<div class="inline-flex items-center">
										{{ item.title }}
										<el-tooltip v-if="item.tooltip" effect="dark" :content="item.tooltip"
											placement="top">
											<el-icon class="ml-2" :size="14">
												<ChatDotRound />
											</el-icon>
										</el-tooltip>
									</div>
								</template>
							</el-statistic>
						</div>
					</el-card>
				</div>

				<div class="grid grid-flow-row grid-cols-1 gap-3 lg:grid-cols-2 xl:grid-cols-3">
					<el-card v-for="items in ['fttr', 'zuwang', 'kanjia', 'mensuo', 'pinganxiangcun']" :key="items"
						body-style="padding: 16px 0 10px;">
						<div class="flex justify-around divide-x divide-dashed">
							<el-statistic v-for="(item, index) in statisticCard[items]" :key="index" :title="item.title"
								:value="item.value" class="flex-1 px-6" />
						</div>
					</el-card>
				</div>

			</div>
			<div class="col-span-1">

				<div class="bg-yellow-400  h-96 xl:h-full">
					<myChart bodyClass="w-full h-full" name="ZaiTuQingKuang" :getDomRef="getDomRef" title=""
						:focusChart="focusChart" @toggle-focus="(e) => (focusChart = e)" />
				</div>
			</div>

		</div>

		<departmentCheckbox v-if="!focusChart" @doSelected="changeSelectedDepartment" />

		<div class="flex flex-col w-full py-6 space-y-10">
			<div class="flex flex-col items-center flex-1 md:items-start" v-for="name in ['ChartA', 'ChartB', 'ChartC']"
				:key="name">
				<el-radio-group class="m-0" v-if="name === 'ChartA'" v-model="bizSelected" @change="bizSelectedChange"
					size="small">
					<el-radio-button v-for="{ name, title } in bizInfo" :key="name" :label="name">{{ title
					}}</el-radio-button>
				</el-radio-group>
				<el-radio-group class="m-0" v-if="name === 'ChartB'" v-model="showModelChartB"
					@change="(label) => showModelChange(label, name)">
					<el-radio-button label="all">所有</el-radio-button>
					<el-radio-button v-if="includesDepartment1" label="region">只展示区域</el-radio-button>
					<el-radio-button v-if="includesDepartment2" label="grid">只展示网格</el-radio-button>
				</el-radio-group>
				<el-radio-group class="m-0" v-if="name === 'ChartC'" v-model="showModelChartC"
					@change="(label) => showModelChange(label, name)">
					<el-radio-button label="all">所有</el-radio-button>
					<el-radio-button v-if="includesDepartment1" label="region">只展示区域</el-radio-button>
					<el-radio-button v-if="includesDepartment2" label="grid">只展示网格</el-radio-button>
				</el-radio-group>
				<myChart bodyClass="w-full h-96" :name="name" :getDomRef="getDomRef" title="" :focusChart="focusChart"
					@toggle-focus="(e) => (focusChart = e)" />

        <myTable v-if="name === 'ChartC' && ztTableRows.length" 
          :columns="ztTableCols"
          :data="ztTableRows"
        />
			</div>

			<!-- <div class="flex flex-1">
				<myChart :bodyClass="[isMobile ? 'h-[50rem]' : 'h-96', 'w-full']" name="topStaff" :getDomRef="getDomRef"
					title="" :focusChart="focusChart" @toggle-focus="(e) => (focusChart = e)" />
			</div> -->

		</div>
	</el-scrollbar>
</template>

<script setup>
import * as echarts from 'echarts';
import { ChatDotRound } from '@element-plus/icons-vue';
import { ref, reactive, onMounted } from 'vue';
import myChart from '@/common/components/myChart.vue';
import departmentCheckbox from '@/common/components/departmentCheckbox.vue';
import myTable from '@/common/components/table.vue';
import datePicker from '@/common/components/datePicker.vue';
import department from '@/common/getDepartment';
import filterData from '@/common/filterData';
import formatter from '@/common/formatter';
import targetRule from '@/common/targetRule';
import { watchResize, watchFocus } from './logic';
import { getListZaiTu } from '@/common/getData';

const { isMobile, allDates } = window;
const selectedDate = ref(allDates[allDates.length - 1])
const changeDate = (days) => {
	selectedDate.value = days;
	updateStatisticCard();
}


const getOptionFn = () => import('@/components/options/getOption');
const { department1, department2 } = department;
const { dataPool } = defineProps(['dataPool']),
	{ dataPool1, dataPool2, topStaff } = dataPool;

const focusChart = ref(''),
	domChart = reactive({});
const charts = window.allCharts['XinYeWu'];
const getDomRef = (name) => (el) => (domChart[name] = ref(el));

const includesDepartment1 = ref(true),
	includesDepartment2 = ref(false),
	selectedDepartment = ref([[], []]),
	mergeDepartment = ref([]),
	changeSelectedDepartment = (e) => {
		selectedDepartment.value = e;
		mergeDepartment.value = department.mergeSelection(selectedDepartment.value);
		includesDepartment1.value = department1.some(value => e.flat().includes(value)) || !e.flat().length;
		includesDepartment2.value = department2.flat().some(value => e.flat().includes(value));
		updateStatisticCard();

		Object.keys(charts).forEach((name) => {
			const option = charts[name].option;

			if (option.getChartData) {
				const newData = option.getChartData([dataPool1, dataPool2, topStaff], e, bizSelected.value);
				sourceCache[name] = newData;
			}
			charts[name].setOption(option)
		});
		showModelChartB.value = 'all'
		showModelChartC.value = 'all'
	};

const statisticCard = reactive({
	kpi: [
		{ name: 'xinyewu_jishilv' },
		{ name: 'xinyewu_huidanlv' },
		{ name: 'xinyewu_zaituguidangbi' },
		{ name: 'xinyewu_renjunchanneng' },
		{ name: 'xinyewu_zhijiantongguolv' }
	],
	fttr: [
		{ title: 'FTTR派单', formatter: (e) => e, func: 'count', param: () => ([dataPool1.xinyewu_xp.FTTR, selectedDepartment.value.flat(), 'max']) },
		{ title: 'FTTR归档', formatter: (e) => e, func: 'count', param: () => ([dataPool1.xinyewu_gd.FTTR, selectedDepartment.value.flat(), 'max']) },
		{ title: 'FTTR在途', formatter: (e) => e, func: 'count', param: () => ([dataPool1.xinyewu_zt.FTTR, selectedDepartment.value.flat(), 'max']) }
	],
	zuwang: [
		{
			title: '组网派单',
			func: 'count',
			param: () => [
				dataPool1.xinyewu_xp.zuwang,
				selectedDepartment.value.flat(),
				'max'
			],
		},
		{
			title: '组网归档',
			func: 'count',
			param: () => [
				dataPool1.xinyewu_gd.zuwang,
				selectedDepartment.value.flat(),
				'max'
			],
		},
		{
			title: '组网在途',
			func: 'count',
			param: () => [
				dataPool1.xinyewu_zt.zuwang,
				selectedDepartment.value.flat(),
				'max'
			],
		},
	],
	kanjia: [
		{ title: '看家派单', func: 'count', param: () => ([dataPool1.xinyewu_xp.kanjia, selectedDepartment.value.flat(), 'max']) },
		{ title: '看家归档', func: 'count', param: () => ([dataPool1.xinyewu_gd.kanjia, selectedDepartment.value.flat(), 'max']) },
		{ title: '看家在途', func: 'count', param: () => ([dataPool1.xinyewu_zt.kanjia, selectedDepartment.value.flat(), 'max']) }
	],
	mensuo: [
		{ title: '门锁派单', func: 'count', param: () => ([dataPool1.xinyewu_xp.mensuo, selectedDepartment.value.flat(), 'max']) },
		{ title: '门锁归档', func: 'count', param: () => ([dataPool1.xinyewu_gd.mensuo, selectedDepartment.value.flat(), 'max']) },
		{ title: '门锁在途', func: 'count', param: () => ([dataPool1.xinyewu_zt.mensuo, selectedDepartment.value.flat(), 'max']) }
	],
	pinganxiangcun: [
		{ title: '平安乡村派单', func: 'count', param: () => ([dataPool1.xinyewu_xp.pinganxiangcun, selectedDepartment.value.flat(), 'max']) },
		{ title: '平安乡村归档', func: 'count', param: () => ([dataPool1.xinyewu_gd.pinganxiangcun, selectedDepartment.value.flat(), 'max']) },
		{ title: '平安乡村在途', func: 'count', param: () => ([dataPool1.xinyewu_zt.pinganxiangcun, selectedDepartment.value.flat(), 'max']) }
	]
});
statisticCard.kpi.forEach(item => {
	Object.assign(
		item,
		targetRule[item.name],
		{
			func: 'kpi',
			getStyle: function (value) { return `color:${formatter.getKpiColor(this, value)};` },
			param: () => [dataPool2[item.name], mergeDepartment.value],
			formatter: (v) => formatter.valueToText(v, targetRule[item.name].isPercent),
		}
	);
	const KPI_CALSS = '智家业务';
	if (item.title.startsWith(KPI_CALSS)) item.title = item.title.slice(KPI_CALSS.length);
});
const updateStatisticCard = () => {
	Object.keys(statisticCard).forEach((key) => {
		statisticCard[key].forEach((item) => {
			item.value = filterData[item.func](...item.param(), selectedDate.value);
		});
	});
};

// --------------------------智家业务时间范围柱状图---------------------------------
const bizInfo = [
	{ name: 'all', title: '总体' },
	{ name: 'FTTR', title: 'FTTR' },
	{ name: 'zuwang', title: '组网' },
	{ name: 'kanjia', title: '看家' },
	{ name: 'mensuo', title: '门锁' },
	{ name: 'pinganxiangcun', title: '平安乡村' }
];
const bizSelected = ref(bizInfo[0].name);

const bizSelectedChange = (v) => {
	const chartInstace = charts['ChartA'];
	const option = chartInstace.option;
	option.getChartData([dataPool1], selectedDepartment.value, v);
	option.title.text = bizInfo.find(i => i.name === v).title;
	chartInstace.setOption(option);
	chartInstace.option = option;
};

// --------------------------智家业务区域范围柱状图---------------------------------
const sourceCache = {};
const showModelChartB = ref('all');
const showModelChartC = ref('all');
const showModelChange = (v, name) => {
	const chartInstance = charts[name];
	const option = chartInstance.option;
	const newSource = sourceCache[name].filter((d, index) => {
		if (index === 0 || v === 'all') return true;
		if (v === 'region') {
			return department1.includes(d[0]);
		}
		if (v === 'grid') {
			return department2.flat().includes(d[0]);
		}
	});
	option.dataset.source = newSource;
	chartInstance.setOption(option);
};

const ztTableCols = reactive([]),
	ztTableRows = reactive([]);

onMounted(async () => {
	updateStatisticCard();

	Object.keys(domChart).forEach(async (chart) => {
		const getOption = (await getOptionFn()).default
		const option = await getOption('XinYeWu', chart);
		if (option.getChartData) {
			const newData = option.getChartData([dataPool1, dataPool2, topStaff]);
			sourceCache[chart] = newData;
		}
		charts[chart] = echarts.init(domChart[chart]);
		charts[chart].setOption(option);
		charts[chart].option = option;

		if (chart === 'ChartC') {
			charts[chart].on('click', async function (params) {
				const seriesNames = [
					{ name: 'chaochang', text: '超长' },
					{ name: 'yujing', text: '预警' },
					{ name: 'vip', text: 'VIP' }
				];
				const seriesName = (seriesNames.find(item => item.text === params.seriesName) || {}).name,
					departmentName = params.name,
					departmentField = department.department1.includes(departmentName) ? 'region' : 'grid';

				const data = {
					collection: 'xinyewu_zt',
					where: { [departmentField]: departmentName }
				};
				if (seriesName) data.where[seriesName] = '是';
				const listZaiTu = await getListZaiTu(data);
				console.log('listZaiTu', listZaiTu);
				const fieldName = [
					{ paidanshijian: '派单时间' },
					{ id: '宽带账号' },
					{ region: '区域' },
					{ grid: '网格' },
					{ staff: '装维人员' },
					{ dizhi: '地址' }
				],
					fieldWidth = [120, 120, 80, 80, 80, 380];
				const { tableCols, tableRows } = filterData.getTableData(fieldName, fieldWidth, listZaiTu);
				tableRows.forEach(item => { item['col-0'] = formatter.excelDate(item['col-0']) });
				ztTableCols.splice(0, ztTableCols.length);
				ztTableCols.push(...tableCols);
				ztTableRows.splice(0, ztTableRows.length);
				ztTableRows.push(...tableRows);
			});
		}

	});

	watchFocus(focusChart, charts);
	watchResize(charts);
});
</script>

<style scoped>
.el-card {
	flex: 1;
}
</style>